/*
 * Copyright (C) 2009, 2010, B3log Team
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.b3log.nide.jsonrpc;

import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import org.b3log.latke.action.ActionException;
import org.b3log.latke.jsonrpc.AbstractJSONRpcService;
import org.b3log.latke.service.ServiceException;
import org.b3log.latke.util.Strings;
import org.b3log.nide.model.NideFile;
import org.b3log.nide.service.JavaSyntaxHighlighter;
import org.b3log.nide.service.ProjectManager;
import org.b3log.nide.util.parser.Style;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * Project service for JavaScript client.
 *
 * @author <a href="mailto:DL88250@gmail.com">Liang Ding</a>
 * @version 1.0.1.0, Nov 29, 2010
 */
public final class ProjectService extends AbstractJSONRpcService {

    /**
     * Default serial version uid.
     */
    private static final long serialVersionUID = 1L;
    /**
     * Logger.
     */
    private static final Logger LOGGER = 
            Logger.getLogger(ProjectService.class.getName());
    /**
     * Project manager.
     */
    private ProjectManager projectManager = ProjectManager.INSTANCE;
    /**
     * Java source syntax highlighter.
     */
    private JavaSyntaxHighlighter javaSyntaxHighlighter =
            JavaSyntaxHighlighter.INSTANCE;

    /**
     * Gets a file by the specified request json object. The file content
     * transformed into a two-dimensional array, every element in the array is
     * a string of one character. The style of the file is also a
     * two-dimensional array, which depicts the style of every character of its
     * content. 
     *
     * Fills "" there is no character at a designated location.
     *
     * @param requestJSONObject the specified request json object, for example:
     * <pre>
     * {
     *     "filePath": "nide-test/pom.xml"
     * }
     * </pre>
     * @param request the specified http servlet request
     * @return for example:
     * <pre>
     * {
     *     "fileName": "nide"
     *     "fileContentMatrix": [["a", "b", " ", ...],
     *                           ["C", "d", " ", ...], ...],
     *     "fileStyleMatrix": [[{"fileStyleCharColor": "#FF0000"},
     *                          {"fileStyleCharColor": "#FF0000"}, ...],
     *                         [{"fileStyleCharColor": "#000000"},
     *                          {"fileStyleCharColor": "#000000"}, ...], ...]
     * }
     * </pre>
     * @throws ActionException action exception
     */
    public JSONObject getFileAsMatrix(final JSONObject requestJSONObject,
                                      final HttpServletRequest request)
            throws ActionException {
        final JSONObject ret = new JSONObject();
        String filePath = null;

        try {
            filePath = requestJSONObject.getString(NideFile.FILE_PATH);
        } catch (final JSONException e) {
            LOGGER.log(Level.SEVERE, e.getMessage(), e);
            throw new ActionException(e);
        }


        String fileName = null;
        try {
            final JSONObject file = projectManager.getFile(filePath);
            fileName = file.getString(NideFile.FILE_NAME);
            ret.put(NideFile.FILE_NAME, fileName);

            final JSONArray contentMatrix = getContentMatrix(file);
            ret.put(NideFile.FILE_CONTENT_MATRIX, contentMatrix);
            final JSONArray styleMatrix = getStyleMatrix(file);
            ret.put(NideFile.FILE_STYLE_MATRIX, styleMatrix);

//            LOGGER.debug("Got file[fileName=" + fileName
//                         + ", fileContentMatrix="
//                         + contentMatrix.toString(Nide.INDENT) + ", fileStyleMatrix="
//                         + styleMatrix.toString(Nide.INDENT) + "]");
        } catch (final Exception e) {
            LOGGER.log(Level.SEVERE, e.getMessage(), e);
            throw new ActionException(e);
        }

        return ret;
    }

    /**
     * Gets a file by the specified request json object.
     *
     * @param requestJSONObject the specified request json object, for example:
     * <pre>
     * {
     *     "filePath": "nide-test/pom.xml"
     * }
     * </pre>
     * @param request the specified http servlet request
     * @return for example:
     * <pre>
     * {
     *     "fileName": "nide"
     *     "fileContent": "The content of a text file...."
     * }
     * </pre>
     * @throws ActionException action exception
     */
    public JSONObject getFile(final JSONObject requestJSONObject,
                              final HttpServletRequest request)
            throws ActionException {
        JSONObject ret = null;
        String filePath = null;

        try {
            filePath = requestJSONObject.getString(NideFile.FILE_PATH);
        } catch (final JSONException e) {
            LOGGER.log(Level.SEVERE, e.getMessage(), e);
            throw new ActionException(e);
        }

        try {
            ret = projectManager.getFile(filePath);
        } catch (final ServiceException e) {
            LOGGER.log(Level.SEVERE, e.getMessage(), e);
            throw new ActionException(e);
        }

        return ret;
    }

    /**
     * Gets a file by the specified request json object.
     *
     * @param requestJSONObject the specified request json object, for example:
     * <pre>
     * {
     *     "filePath": "nide-test/pom.xml",
     *     "fileContent": "...."
     * }
     * </pre>
     * @return for example:
     * <pre>
     * {
     * TODO
     * }
     * </pre>
     * @throws ActionException action exception
     */
    public JSONObject saveFile(final JSONObject requestJSONObject)
            throws ActionException {
        JSONObject ret = null;
        String filePath = null;
        String fileContent = null;

        try {
            filePath = requestJSONObject.getString(NideFile.FILE_PATH);
            fileContent = requestJSONObject.getString(NideFile.FILE_CONTENT);
        } catch (final JSONException e) {
            LOGGER.log(Level.SEVERE, e.getMessage(), e);
            throw new ActionException(e);
        }

        try {
            ret = projectManager.saveFile(filePath, fileContent);
        } catch (final ServiceException e) {
            LOGGER.log(Level.SEVERE, e.getMessage(), e);
            throw new ActionException(e);
        }

        return ret;
    }

    /**
     * Gets project space tree with the specified request json object.
     *
     * @param requestJSONObject the specified request json object
     * @param request the specified http servlet request
     * @return a project space tree
     * @throws ActionException action exception
     */
    public JSONObject getProjectSpaceTree(final JSONObject requestJSONObject,
                                          final HttpServletRequest request)
            throws ActionException {
        JSONObject ret = null;

        try {
            ret = projectManager.genProjectSpaceTree(
                    ProjectManager.getProjectsDir());
        } catch (final ServiceException e) {
            LOGGER.log(Level.SEVERE, e.getMessage(), e);
            throw new ActionException(e);
        }

        return ret;
    }

    /**
     * Gets content matrix for the specified file.
     *
     * @param file the specified file
     * @return content matrix
     * @throws Exception exception
     */
    private JSONArray getContentMatrix(final JSONObject file) throws Exception {
        final JSONArray ret = new JSONArray();

        final String content = file.getString(NideFile.FILE_CONTENT);
        final List<String> lines = Strings.toLines(content);
        String lineString = "";
        for (int i = 0; i < lines.size(); i++) {
            lineString = lines.get(i);
            final char[] chars = lineString.toCharArray();
            ret.put(new JSONArray(chars));
        }

        return ret;
    }

    /**
     * Gets style matrix for the specified file.
     *
     * @param file the specified file
     * @return style matrix
     * @throws Exception exception
     */
    private JSONArray getStyleMatrix(final JSONObject file)
            throws Exception {
        final JSONArray ret = new JSONArray();

        final String content = file.getString(NideFile.FILE_CONTENT);
        final List<String> lines = Strings.toLines(content);
        String lineString = "";
        for (int i = 0; i < lines.size(); i++) {
            lineString = lines.get(i);
            final JSONArray lineStyles = new JSONArray();
            ret.put(lineStyles);

            for (int j = 0; j < lineString.length(); j++) {
                JSONObject fileStyleChar = null;
                if (file.getString(NideFile.FILE_NAME).endsWith(".java")) {
                    fileStyleChar = javaSyntaxHighlighter.getHighlighting(
                            content, i + 1, j + 1);
                } else { // TODO: syntax highlighting
                    fileStyleChar = new JSONObject();
                    final Style style = new Style();
                    fileStyleChar.put(NideFile.FILE_STYLE_CHAR_COLOR,
                                      style.getColor());
                    fileStyleChar.put(NideFile.FILE_STYLE_CHAR_FONT_WEIGHT,
                                      style.getFontWeight());
                    fileStyleChar.put(NideFile.FILE_STYLE_CHAR_FONT_STYLE,
                                      style.getFontStyle());
                }

                lineStyles.put(fileStyleChar);
            }
        }

        return ret;
    }
}
